package com.monster.multithreading;

/**
 * description:
 * 线程等待与唤醒
 * @author Yuanml on 2021/4/2 15:43
 */
public class WaitAndNotify {
    private static final Object o = new Object();
    private static boolean isWake = false;
    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            System.out.println("子线程启动");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("子线程唤醒主线程");
            synchronized (o) {
                isWake = true;
                o.notifyAll();
            }
        }).start();

        synchronized (o) {
            System.out.println("main线程进入等待");
            // 为避免虚假唤醒，我们应该在一个循环中调用wait()方法，退出循环的条件为唤醒该线程的条件
            while (!isWake) {
                o.wait();
            }
            System.out.println("main线程结束运行");
        }
    }
}
